package com.example.mysaat.service_menu_manual_test.AllFunctions;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.util.Log;

import com.example.mysaat.service_menu_manual_test.allActivities.AutoPressActivity;

public class EarPhoneInspect {
    private AudioManager audioManager = null;
    private Activity activity = null;
    private static final int HEADSET_PLUG_IN_STATE = 1;
    private static final int HEADSET_PLUG_OUT_STATE = 0;
    private static final int HEADSET_WITH_MIC = 1;
    private static boolean isHeadsetInsert=false;
    private static boolean hasMic=false;
    private static final String TAG = "EarPhoneInspect";
    public Boolean isRegister = false;


    public EarPhoneInspect(Activity activity){
        this.activity = activity;
        audioManager = (AudioManager) this.activity.getSystemService(Context.AUDIO_SERVICE);
    }


    public boolean isHeadsetPass(){
        IntentFilter filter = new IntentFilter(Intent.ACTION_HEADSET_PLUG);
        this.activity.registerReceiver(broadcastReceiver,filter);
        isRegister = true;
        return isHeadsetInsert;
    }

    //当耳机插入和拔出时，系统就会发送广播
    private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if(context ==null)
                return;
            ((AutoPressActivity)activity).updateEarphoneStatus();
            String action = intent.getAction();
            if(Intent.ACTION_HEADSET_PLUG.equals(action)){
                //get the value of microphone,if have not a value return 0
                int headsetType = intent.getIntExtra("microphone",0);
                int state = intent.getIntExtra("state",HEADSET_PLUG_OUT_STATE);
                if(state==HEADSET_PLUG_IN_STATE)
                    isHeadsetInsert = true;

                if (state == HEADSET_PLUG_OUT_STATE)
                    isHeadsetInsert = false;

                Log.d(TAG, "onReceive: "+isHeadsetInsert);
                hasMic = headsetType==HEADSET_WITH_MIC?true:false;
            }
        }
    };

    public void mUnregisterBroadcast(){
        this.activity.unregisterReceiver(broadcastReceiver);
    }
}
